package Java基础.线程池;


import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Title 线程池测试
 * @Author zhengqiang.tan
 * @Date 2021/3/28 4:02 PM
 */
public class T02_ThreadPoolTest {
    static class Task implements Runnable {
        private int i;

        public Task(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Task " + i);
            try {
                System.in.read(); // 打印后阻塞
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "Task{" +
                    "i=" + i +
                    '}';
        }
    }

    public static void main(String[] args) {
        // 7 params
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(
                2,
                4,
                60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        tpe.allowCoreThreadTimeOut(true); // 线程池数量最后销毁到0个

        for (int i = 0; i < 8; i++) {
            tpe.execute(new Task(i));
        }
        System.out.println("queue size:" + tpe.getQueue().size());

        tpe.execute(new Task(10)); // 满4个后有调用者处理，这里是main


        System.out.println("queue size:" + tpe.getQueue().size());
        tpe.shutdownNow();

    }
}
//        pool-1-thread-1 Task 0
//        pool-1-thread-2 Task 1
//        pool-1-thread-3 Task 6
//        pool-1-thread-4 Task 7
//        queue size:4
//        main Task 10
